/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use std::future::Future;
use std::pin::Pin;
use common_log::info;
use super::super::traits::{InitContext, InitHandler};

#[derive(Debug)]
pub struct LoggerInitHandler {
    next: Option<Box<dyn InitHandler>>,
}

impl LoggerInitHandler {
    pub fn new() -> LoggerInitHandler {
        LoggerInitHandler { next: None }
    }

    /// Initializes the logger based on the build configuration.
    /// 
    /// # Panics
    /// 
    /// This function will panic if it fails to initialize the logger
    pub fn init_logger(&self) {
        common_log::init_with_default_path().expect("failed to init logger");
        info!("Logger initialized");
    }
}

impl InitHandler for LoggerInitHandler {
    fn handle<'a>(&'a self, context: &'a mut InitContext) -> Pin<Box<dyn Future<Output=Result<(), String>> + 'a>> {
        Box::pin(async move {
            self.init_logger();
            if let Some(next) = &self.next {
                next.handle(context).await
            } else {
                Ok(())
            }
        })
    }

    fn set_next(&mut self, next: Box<dyn InitHandler>) {
        self.next = Some(next);
    }
}
